<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZooKeeper 管理工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }
        body {
            display: flex;
            height: 100vh;
        }
        #tree-container {
            width: 40%;
            border-right: 1px solid #ccc;
            overflow-y: auto;
            padding: 10px;
        }
        #content-container {
            width: 60%;
            display: flex;
            flex-direction: column;
            padding: 10px;
        }
        #node-content {
            flex-grow: 1;
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 10px;
            resize: none;
            font-family: monospace;
        }
        #save-btn {
            align-self: flex-end;
            padding: 8px 16px;
            margin-top: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #save-btn:hover {
            background-color: #45a049;
        }
        .tree-node {
            padding: 5px;
            cursor: pointer;
            border-radius: 3px;
        }
        .tree-node:hover {
            background-color: #f0f0f0;
        }
        .tree-node.selected {
            background-color: #e0e0ff;
        }
        .tree-children {
            margin-left: 20px;
            display: none;
        }
        .tree-children.expanded {
            display: block;
        }
        .expand-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            text-align: center;
            margin-right: 5px;
        }
        .context-menu {
            position: absolute;
            background-color: white;
            border: 1px solid #ccc;
            box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
            display: none;
        }
        .context-menu-item {
            padding: 5px 10px;
            cursor: pointer;
        }
        .context-menu-item:hover {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <div id="tree-container"></div>
    <div id="content-container">
        <h2>节点内容</h2>
        <textarea id="node-content"></textarea>
        <button id="save-btn">保存</button>
    </div>

    <div id="context-menu" class="context-menu">
        <div class="context-menu-item" id="create-node">创建节点</div>
        <div class="context-menu-item" id="delete-node">删除节点</div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const treeContainer = document.getElementById('tree-container');
            const nodeContent = document.getElementById('node-content');
            const saveBtn = document.getElementById('save-btn');
            const contextMenu = document.getElementById('context-menu');
            let selectedNodePath = null;
            let currentNodeElement = null;
            let ws = null;

            // 连接 WebSocket
            function connectWebSocket() {
                ws = new WebSocket(`ws://${window.location.host}/ws/zk`);

                ws.onopen = function() {
                    console.log('WebSocket 连接成功');
                    // 请求监听当前选中的节点
                    if (selectedNodePath) {
                        ws.send(JSON.stringify({
                            action: 'watch_node',
                            path: selectedNodePath
                        }));
                    }
                };

                ws.onmessage = function(event) {
                    const update = JSON.parse(event.data);
                    if (update.type === 'node_data_changed' && update.path === selectedNodePath) {
                        nodeContent.value = update.data;
                    } else if (update.type === 'children_changed') {
                        // 如果子节点变化，重新加载树
                        loadTree();
                    }
                };

                ws.onclose = function() {
                    console.log('WebSocket 连接关闭');
                    // 尝试重新连接
                    setTimeout(connectWebSocket, 3000);
                };

                ws.onerror = function(error) {
                    console.error('WebSocket 错误:', error);
                };
            }

            // 加载 ZooKeeper 树
            function loadTree() {
                fetch('/api/zk/tree')
                    .then(response => response.json())
                    .then(tree => {
                        treeContainer.innerHTML = '';
                        renderTreeNode(treeContainer, tree, '/');
                    })
                    .catch(error => console.error('加载树失败:', error));
            }

            // 渲染树节点
            function renderTreeNode(container, node, path) {
                const nodeElement = document.createElement('div');
                nodeElement.className = 'tree-node';
                nodeElement.dataset.path = path;

                // 如果是根节点
                if (path === '/') {
                    nodeElement.textContent = '/';
                } else {
                    // 获取节点名称（路径的最后一部分）
                    const parts = path.split('/');
                    const nodeName = parts[parts.length - 1];
                    nodeElement.textContent = nodeName;
                }

                // 如果有子节点
                if (node.children) {
                    const expandIcon = document.createElement('span');
                    expandIcon.className = 'expand-icon';
                    expandIcon.textContent = '+';
                    nodeElement.insertBefore(expandIcon, nodeElement.firstChild);

                    const childrenContainer = document.createElement('div');
                    childrenContainer.className = 'tree-children';
                    nodeElement.appendChild(childrenContainer);

                    // 展开/收起功能
                    expandIcon.addEventListener('click', function(e) {
                        e.stopPropagation();
                        childrenContainer.classList.toggle('expanded');
                        expandIcon.textContent = childrenContainer.classList.contains('expanded') ? '-' : '+';
                    });

                    // 渲染子节点
                    for (const childName in node.children) {
                        const childPath = path === '/' ? `/${childName}` : `${path}/${childName}`;
                        renderTreeNode(childrenContainer, node.children[childName], childPath);
                    }
                }

                // 点击节点事件
                nodeElement.addEventListener('click', function() {
                    // 移除之前选中节点的样式
                    if (currentNodeElement) {
                        currentNodeElement.classList.remove('selected');
                    }
                    // 添加当前节点的选中样式
                    nodeElement.classList.add('selected');
                    currentNodeElement = nodeElement;

                    selectedNodePath = path;
                    // 加载节点内容
                    loadNodeContent(path);

                    // 请求监听该节点
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify({
                            action: 'watch_node',
                            path: path
                        }));
                    }
                });

                // 右键菜单事件
                nodeElement.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    // 选中当前节点
                    if (currentNodeElement) {
                        currentNodeElement.classList.remove('selected');
                    }
                    nodeElement.classList.add('selected');
                    currentNodeElement = nodeElement;
                    selectedNodePath = path;

                    // 显示右键菜单
                    contextMenu.style.top = `${e.clientY}px`;
                    contextMenu.style.left = `${e.clientX}px`;
                    contextMenu.style.display = 'block';
                });

                container.appendChild(nodeElement);
            }

            // 加载节点内容
            function loadNodeContent(path) {
                fetch(`/api/zk/node?path=${encodeURIComponent(path)}`)
                    .then(response => response.text())
                    .then(content => {
                        nodeContent.value = content;
                    })
                    .catch(error => console.error('加载节点内容失败:', error));
            }

            // 保存节点内容
            saveBtn.addEventListener('click', function() {
                if (!selectedNodePath) {
                    alert('请先选择一个节点');
                    return;
                }

                fetch(`/api/zk/node?path=${encodeURIComponent(selectedNodePath)}`, {
                    method: 'POST',
                    body: nodeContent.value
                })
                    .then(response => response.text())
                    .then(result => {
                        if (result === 'OK') {
                            alert('保存成功');
                        } else {
                            alert('保存失败');
                        }
                    })
                    .catch(error => console.error('保存节点内容失败:', error));
            });

            // 右键菜单 - 创建节点
            document.getElementById('create-node').addEventListener('click', function() {
                if (!selectedNodePath) return;

                const newNodeName = prompt('请输入新节点名称:');
                if (!newNodeName) return;

                const newNodePath = selectedNodePath === '/' ? `/${newNodeName}` : `${selectedNodePath}/${newNodeName}`;
                const newNodeData = prompt('请输入节点数据:') || '';

                fetch(`/api/zk/node/create?path=${encodeURIComponent(newNodePath)}`, {
                    method: 'POST',
                    body: newNodeData
                })
                    .then(response => response.text())
                    .then(result => {
                        if (result === 'OK') {
                            alert('创建成功');
                            loadTree();
                        } else {
                            alert('创建失败');
                        }
                    })
                    .catch(error => console.error('创建节点失败:', error));

                contextMenu.style.display = 'none';
            });

            // 右键菜单 - 删除节点
            document.getElementById('delete-node').addEventListener('click', function() {
                if (!selectedNodePath) return;

                if (confirm(`确定要删除节点 ${selectedNodePath} 吗?`)) {
                    fetch(`/api/zk/node?path=${encodeURIComponent(selectedNodePath)}`, {
                        method: 'DELETE'
                    })
                        .then(response => response.text())
                        .then(result => {
                            if (result === 'OK') {
                                alert('删除成功');
                                loadTree();
                                nodeContent.value = '';
                                selectedNodePath = null;
                            } else {
                                alert('删除失败');
                            }
                        })
                        .catch(error => console.error('删除节点失败:', error));
                }

                contextMenu.style.display = 'none';
            });

            // 点击空白处关闭右键菜单
            document.addEventListener('click', function() {
                contextMenu.style.display = 'none';
            });

            // 初始化
            connectWebSocket();
            loadTree();
        });
    </script>
</body>
</html>
